import {message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {ActionType, EditableProTable, ProColumns} from '@ant-design/pro-table';
import {list, removeById, save} from '../service/baseService';
import {DataEntity} from "@/assets/entity/base";
import {TableListProps} from "@/assets/components/tableListProps";

/**
 * 列表组件
 * @param props
 * @constructor
 */
const EditTableList = (props: TableListProps) => {
  const actionRef = useRef<ActionType>();
  // const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const moduleUrl: String = props.moduleUrl;
  const columns: ProColumns<DataEntity>[] = props.columns.concat({
    title: '操作',
    valueType: 'option',
    render: (_, record: DataEntity, __, action) => [
      <a onClick={() => {
        record.id ? action.startEditable?.(record.id) : message.error('系统错误，请联系管理员');
      }}>编辑</a>,
      <a
        onClick={() => {
          Modal.confirm({
            title: '删除',
            content: '确定删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => handleRemove(record.id),
          });
        }}
      >
        删除
      </a>
    ]
  });

  /**
   * 保存（添加或修改）节点
   */
  const handleSave = async (key: any, row: DataEntity) => {
    const hide = message.loading('正在保存');
    try {
      await save(moduleUrl, row);
      hide();
      message.success('保存成功');
      return true;
    } catch (error) {
      message.error('保存失败，请重试');
      hide();
      return false;
    }
  };

  /**
   *  删除单个节点
   * @param id
   */
  const handleRemove = async (id: string | undefined) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
      await removeById(moduleUrl, id);
      hide();
      message.success('删除成功，即将刷新');
      // @ts-ignore 重载表格
      actionRef.current.reload()
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  // @ts-ignore
  return (
    <PageContainer>
      <EditableProTable<DataEntity>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        editable={{
          editableKeys,
          onSave: handleSave,
          onChange: setEditableRowKeys,
        }}
        search={{
          labelWidth: 120,
        }}
        request={(params, sorter, filter) => list(moduleUrl, {...params})}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        // }}
        recordCreatorProps={{
          // 顶部添加还是末尾添加
          position: 'bottom',
          // 不写 key ，会使用 index 当行 id
          record: {},
        }}
      />
    </PageContainer>
  );
};

export default EditTableList;
